<template>
    <el-dialog :modal-append-to-body="false" title="选择表字段" :visible.sync="isCommonModalTemplate">
        <!-- <avue-form ref="form" :option="queryOption" v-model="form">
            <template slot="menuForm" style="text-align: right;">
                <el-button icon="el-icon-search" type="primary" @click="handleSubmit">搜 索</el-button>
                <el-button icon="el-icon-delete" @click="handleEmpty">清 空</el-button>
            </template>
        </avue-form> -->
        <div class="row">
            <div class="col-lg-8 col-xs-8 ag-grid-resource-col">
                <!-- <ag-grid-vue class="ag-theme-material ag-theme-custom-status-bar" :gridOptions="gridOptions"
                    @grid-ready="onGridReady" @row-double-clicked="onRowDoubleClicked">
                </ag-grid-vue>
                <ag-custom-status-bar [gridApi]="gridApi" [gridOptions]="gridOptions" (onRefresh)="createRowData()"
                    [(pageSize)]="PAGE_SIZE" [(totalRow)]="gridOptions.infiniteInitialRowCount"></ag-custom-status-bar> -->
                <avue-crud ref="crud" :data="data" :option="tableOption" :search.sync="search" @search-change="searchChange" :page.sync="page"
                    @on-load="onLoad" @selection-change="selectionChange" @row-click="rowClick" @row-dblclick="rowDbclick"></avue-crud>
            </div>
            <div class="col-lg-4 col-xs-4 ag-grid-target-col">
                <div class="control-icons">
                    <p>
                        <i class="material-icons" @click="addToRight()">keyboard_arrow_right</i>
                    </p>
                    <p>
                        <i class="material-icons" @click="removeToLeft()">keyboard_arrow_left</i>
                    </p>
                </div>
                <avue-crud ref="targetCrud" :data="targetData" :option="targetTableOption" @selection-change="targetSelectionChange" @row-click="targetRowClick" @row-dblclick="targetRowDbclick"></avue-crud>
                <!-- <ag-grid-vue style="height: 500px;min-height: 500px;" class="ag-theme-material"
                    :gridOptions="targetGridOptions" @grid-ready="onTargetGridReady"
                    @row-double-clicked="onTargetRowDoubleClicked">
                </ag-grid-vue> -->
            </div>
        </div>
        <div class="row text-right m--padding-right-15">
            <form>
                <button type="reset" class="btn" (click)="close()">
                    取消
                </button>
                <button type="submit" class="btn btn-primary" (click)="ok()">
                    提交
                </button>
            </form>
        </div>
    </el-dialog>
</template>
<script>
    import Helpers from "@/util/helpers";
    export default {
        components: {
            
        },
        data() {
            return {
                isCommonModalTemplate: false,
                dataSet: [],
                tableNameList: [],
                model: {},
                data: [],
                tableOption: {
                    border: true, //表格外框线是否显示
                    stripe: true, //表格是否显示条纹
                    header: true, //表格头部是否显示
                    index: true, //表格数据序号
                    page: false, //表格分页是否显示
                    addBtn: false, //新增按钮是否显示
                    menu: false, //表格操作栏是否显示
                    refreshBtn: false, //刷新按钮是否显示
                    columnBtn: false, //控制表格列是否显示按钮是否显示
                    searchMenuSpan: 6, //搜索按钮所占宽度
                    searchMenuPosition: 'right', //搜索按钮位置
                    selection: false, //表格是否多选
                    column: [
                        { label: "字段名", prop: "fieldName", search: true },
                        { label: "字段注释", prop: "fieldComment", search: true },
                        { label: "表名", prop: "tableName" },
                        { label: "表注释", prop: "tableComment" }
                    ]
                },
                search: {},
                page: {
                    pageSize: 20,
                    pagerCount: 5,
                    currentPage: 1,
                    total: 0,
                }, //表格分页
                targetData: [],
                targetTableOption: {
                    border: true, //表格外框线是否显示
                    stripe: true, //表格是否显示条纹
                    header: true, //表格头部是否显示
                    index: true, //表格数据序号
                    page: false, //表格分页是否显示
                    addBtn: false, //新增按钮是否显示
                    menu: false, //表格操作栏是否显示
                    refreshBtn: false, //刷新按钮是否显示
                    columnBtn: false, //控制表格列是否显示按钮是否显示
                    selection: false, //表格是否多选
                    column: [
                        { label: "字段名", prop: "fieldName" },
                        { label: "字段注释", prop: "fieldComment" },
                        { label: "表名", prop: "tableName" },
                        { label: "表注释", prop: "tableComment" }
                    ]
                },
                selectedRecordData: [], //多选时选中的记录
            }
        },
        mounthed() {

        },

        methods: {
            modalShow(data) {
                setTimeout(() => {
                    this.dataSet = data;
                    this.isCommonModalTemplate = true;
                    let dataSet = this.dataSet.slice(0);
                    // this.tableNameList = this._map(dataSet, (item) => {
                    //     return {
                    //         label: item.tableComment,
                    //         value: item.tableName,
                    //     }
                    // });
                    this.model.tableName = this._get(this.tableNameList, '[0].tableName', '');
                }, 500);
            },

            createRowData() {
                // let dataSource = {
                //     rowCount: null,
                //     getRows: (params) => {
                //         let pageNum = this.gridApi.paginationGetCurrentPage() + 1;
                //         this.searchParam['tableName'] = this.model.tableName;
                //         let paramMap = Helpers.SearchFormSubmit(pageNum, this.PAGE_SIZE, {}, this.searchParam, params.sortModel);
                //         this.httpService.post(Config.API_URL.COMMON_TABLE.FIND_PAGING_INFO_LIST_URL, paramMap,
                //             (successful, dataSet, res) => {
                //                 if (dataSet.stateCode === 'SYSTEM_SUCCESS') {
                //                     var rowsThisPage = dataSet.data.rows;
                //                     rowsThisPage.length ? this.gridApi.hideOverlay() : this.gridApi.showNoRowsOverlay();
                //                     var lastRow = dataSet.data.total || 0;
                //                     this.gridOptions.infiniteInitialRowCount = lastRow;
                //                     params.successCallback(rowsThisPage, lastRow);
                //                 } else {
                //                     this.$message({
                //                         showClose: true,
                //                         message: dataSet.message,
                //                         type: 'success'
                //                     });
                //                 }
                //             }, (successful, msg, err) => {
                //                 this.$message({
                //                     showClose: true,
                //                     message: msg,
                //                     type: 'error'
                //                 });
                //             });
                //     }
                // };
                // this.gridApi.setDatasource(dataSource);
            },

            searchChange(params, done) {
                done();
                this.$message.success(JSON.stringify(params));
            },

            selectionChange(list) {
                let selectRows = list;
                //多选
                this.selectedRecordData = selectRows.slice(0);
            },

            rowClick(row) {
                this.$refs.crud.toggleRowSelection(row);
            },

            /**
             * 双击事件
             * @param $event
             */
             rowDbclick(row) {
                //去左侧与右侧的并集
                let result = this._union(this.targetData, [row]);
                this.targetData = result;
                //将左侧选中的记录置空为不选中状态
                this.$refs.crud.toggleRowSelection();
            },

            /**
             * 将左边选中的数据添加至右侧表格
             */
            addToRight() {
                if (this.selectedRecordData.length > 0) {

                    //去左侧与右侧的并集
                    let result = this._union(this.targetData, this.selectedRecordData);
                    this.targetData = result;
                    //将左侧选中的记录置空为不选中状态
                    this.$refs.crud.toggleRowSelection();
                    this.selectedRecordData = [];
                } else {
                    this.$message({
                        message: '请选择左侧列表中的数据进行添加！',
                        type: 'warning'
                    });
                }
            },

            /**
             * 右侧表格单击事件
             */
            targetRowClick(row) {
                this.$refs.crud.toggleRowSelection(row);
            },

            /**
             * 右侧表格多选
             */
             targetSelectionChange(list) {
                let selectRows = list;
                //多选
                this.selectedRecordData = selectRows.slice(0);
             },

            /**
             * 将右侧选中的数据移除
             */
            removeToLeft() {
                let selectedData = this.targetGridOptions.api.getSelectedRows();
                if (selectedData.length > 0) {
                    this.targetGridOptions.api.updateRowData({ remove: selectedData });
                } else {
                    this.$message({
                        showClose: true,
                        message: '请选择右侧列表中的数据进行移除！',
                        type: 'warning'
                    });
                }
            },

            /**
             * 将右边移除
             * @param $event
             */
            onTargetRowDoubleClicked($event) {
                this.targetGridOptions.api.updateRowData({ remove: [$event.data] });
            },

            /**
             * 确认修改
             */
            ok() {
                let selectedTargetRecordData = [];
                this.targetGridOptions.api.forEachNode((node) => {
                    selectedTargetRecordData.push(node.data);
                });
                let selectData = {};
                if (selectedTargetRecordData.length > 0) {
                    //获取选中表注释，使用-截取来获取表别名，再匹配到insideCode
                    let tableNameAndAlias = $('#tableName').find('.mat-select-value-text span').text();
                    let tableNameList = tableNameAndAlias.split('-');
                    if (tableNameList.length === 1) {
                        this._forEach(selectedTargetRecordData, (item) => {
                            let findNode = this._find(this.tableNameList, { 'tableName': this.model.tableName });
                            item.insideCode = findNode.insideCode;
                        });
                        this.modalDataService.modalData.multipleSelectedData = selectedTargetRecordData.slice(0);
                    } else if (tableNameList.length === 2) {
                        let tableAlias = this._get(tableNameList, '[1]', '');
                        this._forEach(selectedTargetRecordData, (item) => {
                            let findNode = this._find(this.tableNameList, { 'tableName': this.model.tableName, 'tableAlias': tableAlias });
                            item.insideCode = findNode.insideCode;
                            item.tableAlias = tableAlias;
                        });
                        this.modalDataService.modalData.multipleSelectedData = selectedTargetRecordData.slice(0);
                    } else {
                        this.$message({
                            showClose: true,
                            message: '表别名中有 - 字符，请检查后重新输入!',
                            type: 'error'
                        });
                    }
                    this.$emit('submitData', selectData);
                } else {
                    this.$message({
                        showClose: true,
                        message: '未选择任何记录！',
                        type: 'error'
                    });
                }
            },

            /**
             * 关闭
             */
            close() {
                this.activeModal.close();
            },
            /**
             * 销毁
             */
            dismiss() {
                this.activeModal.dismiss();
            }
        }
    }
</script>